﻿/*

The MIT License

Copyright (c) 2010 Cartesian Analytics, Inc. 

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

using System;

namespace Pipra.Math.Geometry
{
    /// <summary>
    /// A straight line of infinite length defined by a point and a direction.
    /// </summary>
    public class Line2 :
        ILine2<double>,
        IEquatable<Line2>,
        IContainable<Mbr>,
        ICloneable
    {

        public static bool operator ==(Line2 a, Line2 b)
        {
            return ReferenceEquals(a, b) || (!ReferenceEquals(null, a) && a.Equals(b));
        }

        public static bool operator !=(Line2 a, Line2 b)
        {
            return !ReferenceEquals(a, b) && (ReferenceEquals(null, a) || !a.Equals(b));
        }

        /// <summary>
        /// A point which lies on the line.
        /// </summary>
        public Point2 P;

        /// <summary>
        /// The direction of the line from P.
        /// </summary>
        public Vector2 Direction;

        /// <summary>
        /// Constructs a line with infinite length passing though <paramref name="p"/> with direction <paramref name="d"/>.
        /// </summary>
        /// <param name="p">A point on the line.</param>
        /// <param name="d">The direction of the line.</param>
        public Line2(Point2 p, Vector2 d)
        {
            P = p;
            Direction = d;
        }
        /// <summary>
        /// Constructs a line with infinite length passing though <paramref name="p"/> with direction <paramref name="d"/>.
        /// </summary>
        /// <param name="p">A point on the line.</param>
        /// <param name="d">The direction of the line.</param>
        public Line2(IPoint2<double> p, IVector2<double> d)
            : this(new Point2(p),new Vector2(d))
        { }
        /// <summary>
        /// Constructs a line with infinite length passing though both points <paramref name="a"/> and <paramref name="b"/>.
        /// </summary>
        /// <param name="a">A point.</param>
        /// <param name="b">A point.</param>
        public Line2(Point2 a, Point2 b)
            : this(a,b.Difference(a))
        { }
        /// <summary>
        /// Constructs a line with infinite length passing though both points <paramref name="a"/> and <paramref name="b"/>.
        /// </summary>
        /// <param name="a">A point.</param>
        /// <param name="b">A point.</param>
        public Line2(IPoint2<double> a, IPoint2<double> b)
            : this(new Point2(a), new Point2(b))
        { }
        /// <summary>
        /// Constructs a line identical to the given <paramref name="line"/>.
        /// </summary>
        /// <param name="line">A line.</param>
        public Line2(Line2 line)
        {
            P = line.P;
            Direction = line.Direction;
        }
        /// <summary>
        /// Constructs a line identical to the given <paramref name="line"/>.
        /// </summary>
        /// <param name="line">A line.</param>
        public Line2(ILine2<double> line)
            : this(line.A,line.Direction)
        {
        }
        /// <summary>
        /// A point on the line.
        /// </summary>
        IPoint2<double> ICurve2<double>.A
        {
            get { return P; }
        }
        /// <summary>
        /// The result of adding the direction vector to A.
        /// </summary>
        IPoint2<double> ICurve2<double>.B
        {
            get { return P.Add(Direction); }
        }
        /// <summary>
        /// The direction of the line.
        /// </summary>
        IVector2<double> ICurve2<double>.Direction
        {
            get { return Direction; }
        }

        /// <summary>
        /// Indicates whether the current object is equal to another object of the same type.
        /// </summary>
        /// <returns>
        /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
        /// </returns>
        /// <param name="other">An object to compare with this object.</param>
        public bool Equals(Line2 other)
        {
            return !ReferenceEquals(null, other)
                && P.Equals(other.P)
                && Direction.Equals(other.Direction)
            ;
        }

        /// <summary>
        /// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
        /// </summary>
        /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
        /// <returns>
        /// 	<c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
        /// </returns>
        /// <exception cref="T:System.NullReferenceException">
        /// The <paramref name="obj"/> parameter is null.
        /// </exception>
        public override bool Equals(object obj)
        {
            return null != obj
                && (
                    (obj is Line2 && Equals(obj as Line2))
                )
            ;
        }
        /// <summary>
        /// Serves as a hash function for a particular type. 
        /// </summary>
        /// <returns>
        /// A hash code for the current <see cref="T:System.Object"/>.
        /// </returns>
        /// <filterpriority>2</filterpriority>
        public override int GetHashCode()
        {
            return System.Math.Abs(Direction.X).GetHashCode();
        }
        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            return String.Concat('{', P, "},{", Direction, '}');
        }
        /// <summary>
        /// Calculates the distance between this line and <paramref name="p"/>
        /// </summary>
        /// <param name="p">The point to calculate distance to.</param>
        /// <returns>The distance.</returns>
        public double Distance(Point2 p)
        {
            Vector2 v0 = p.Difference(P);
            double m = Direction.GetMagnitudeSquared();
            if (0 != m)
            {
                double aDot = Direction.Dot(v0);
                return System.Math.Sqrt(v0.GetMagnitudeSquared() - ((aDot * aDot) / m));
            }
            return v0.GetMagnitude();
        }
        /// <summary>
        /// Calculates the distance between this line and <paramref name="p"/>
        /// </summary>
        /// <param name="p">The point to calculate distance to.</param>
        /// <returns>The distance.</returns>
        public double Distance(IPoint2<double> p)
        {
            return Distance(new Point2(p));
        }
        /// <summary>
        /// Calculates the squared distance between this line and <paramref name="p"/>
        /// </summary>
        /// <param name="p">The point to calculate squared distance to.</param>
        /// <returns>The squared distance.</returns>
        public double DistanceSquared(Point2 p)
        {
            Vector2 v0 = p.Difference(P);
            double m = Direction.GetMagnitudeSquared();
            if (0 != m)
            {
                double aDot = Direction.Dot(v0);
                return (v0.GetMagnitudeSquared() - ((aDot * aDot) / m));
            }
            return v0.GetMagnitudeSquared();
        }
        /// <summary>
        /// Calculates the squared distance between this line and <paramref name="p"/>
        /// </summary>
        /// <param name="p">The point to calculate squared distance to.</param>
        /// <returns>The squared distance.</returns>
        public double DistanceSquared(IPoint2<double> p)
        {
            return DistanceSquared(new Point2(p));
        }
        /// <summary>
        /// Determines if a <paramref name="p"/> intersects this line.
        /// </summary>
        /// <param name="p">A point.</param>
        /// <returns>True when intersecting.</returns>
        public bool Intersects(Point2 p)
        {
            Vector2 v0 = p.Difference(P);
            double m = Direction.GetMagnitudeSquared();
            if (0 != m)
            {
                double aDot = Direction.Dot(v0);
                return (m * v0.GetMagnitudeSquared()) == (aDot * aDot);
            }
            return 0 == v0.X && 0 == v0.Y;
        }
        /// <summary>
        /// Determines if a <paramref name="p"/> intersects this line.
        /// </summary>
        /// <param name="p">A point.</param>
        /// <returns>True when intersecting.</returns>
        public bool Intersects(IPoint2<double> p)
        {
            return Intersects(new Point2(p));
        }
        /// <summary>
        /// Calculates the length of this line.
        /// </summary>
        /// <returns>The length.</returns>
        public double GetMagnitude()
        {
            return Vector2.ZeroVector == Direction ? 0 : Double.PositiveInfinity;
        }
        /// <summary>
        /// Calculates the squared length of this line.
        /// </summary>
        /// <returns>The length.</returns>
        public double GetMagnitudeSquared()
        {
            return GetMagnitude();
        }
        /// <summary>
        /// Creates a copy of this line.
        /// </summary>
        /// <returns>
        /// A new identical line.
        /// </returns>
        /// <filterpriority>2</filterpriority>
        public Line2 Clone()
        {
            return new Line2(this);
        }

        object ICloneable.Clone()
        {
            return Clone();
        }

        /// <summary>
        /// Calculates a minimum bounding rectangle for this line.
        /// </summary>
        /// <returns>A minimum bounding rectangle.</returns>
        public IMbr<double> GetMbr()
        {
            return (
                (0 == Direction.X)
                ? (
                    (0 == Direction.Y)
                    ? new Mbr(P)
                    : new Mbr(P.X, Double.NegativeInfinity, P.X, Double.PositiveInfinity)
                )
                : (
                    (0 == Direction.Y)
                    ? new Mbr(Double.NegativeInfinity, P.Y, Double.PositiveInfinity, P.Y)
                    : new Mbr(Double.NegativeInfinity, Double.NegativeInfinity, Double.PositiveInfinity, Double.PositiveInfinity)
                )
            );
        }
        IPoint2<double> IHasPlanarCentroid<double>.GetCentroid()
        {
            return P;
        }
        /// <summary>
        /// Determines if the given MBR contains this line.
        /// </summary>
        /// <param name="mbr">The MBR to test.</param>
        /// <returns>True if this line is within the given MBR.</returns>
        public bool Within(Mbr mbr)
        {
            return GetMbr().Within(mbr);
        }
        /// <summary>
        /// Determines if the given MBR contains this line.
        /// </summary>
        /// <param name="mbr">The MBR to test.</param>
        /// <returns>True if this line is within the given MBR.</returns>
        public bool Within(IMbr<double> mbr)
        {
            return GetMbr().Within(mbr);
        }

        bool ISelfIntersectable.IsSelfIntersecting()
        {
            return false;
        }
    }
}
